﻿<%@ WebHandler Language="C#" Class="BusinessMarket" %>

using System;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Data;
using Chenxin.Lib.Utility;
using Chenxin.Lib.Business;
using Chenxin.Lib.Business.BLL;

public class BusinessMarket : AjaxHandlerBase
{
    public BusinessMarket()
    {
        //导出
        htTypePermit.Add("export", Constants.Permit_BusinessMarket_Export);
        htTypePermit.Add("exportall", Constants.Permit_BusinessMarket_Export);
    }
    override public void RequestProcess(HttpContext context)
    {
        try
        {
            context.Response.ContentType = "text/plain";
            context.Response.AddHeader("pragma", "no-cache");
            context.Response.AddHeader("cache-control", "");
            context.Response.CacheControl = "no-cache";

            string strOp = context.Request["op"];
            string strRet = string.Empty;
            switch (strOp.ToLower())
            {
                //添加报备相关信息
                case "getlist":
                    GetList(context);
                    break;
                case "exportall":
                    ExportAll(context);
                    break;
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }


    private void GetList(HttpContext context)
    {
        Guid city = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
        Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
        Guid businessdistrict = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
        Guid departs = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);

        //判断权限范围/////////////////////////////////////////////
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        if (CurrentUserInfo.ContainsPermit(Constants.Permit_BusinessMarket_All))
        {
            sb.Append(" (1=1) ");
        }
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_BusinessMarket_City))
        {
            sb.AppendFormat(" BargainCityId='{0}' ",CurrentUserInfo.CityId);
        }
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_BusinessMarket_Company))
        {
            sb.AppendFormat(" BargainCompanyId='{0}' ", CurrentUserInfo.CompanyId);
        }
        else
        {
            sb.Append(" 1=0 ");
        }
        
        
        if (departs != Guid.Empty)
            sb.AppendFormat(" AND (BuyerDepartId = '{0}')", departs);
        else if (businessdistrict != Guid.Empty)
        {
            Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
            string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, businessdistrict);
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
            if (!cs.Hit)
            {
                item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(businessdistrict);
                if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
            }

            if (item == null)
            {
                context.Response.Write(string.Format("{{success:'0',msg:'{0}',data:''}}", "获取商圈或分类数据丢失"));
                return;
            }
            sb.Append(" AND (EXISTS(");
            sb.Append("Select 1 from v_Hr_DepartmentInfo M ");
            sb.AppendFormat("WHERE (t_Contract_BaseInfo.BuyerDepartId = M.Departid AND M.DepartSrc like '{0}%'))) ", item.DepartSrc);
        }
        else if (company != Guid.Empty)
        {
            sb.AppendFormat(" and BargainCompanyId='{0}' ", company);
        }
        else if (city != Guid.Empty)
        {
            sb.AppendFormat(" and BargainCityId='{0}' ", city);
        }
        else
            sb.AppendFormat(" and BargainCompanyId='{0}' ", CurrentUserInfo.CompanyId);

        if (!String.IsNullOrEmpty(context.Request.Params["region"]))
        {
            sb.AppendFormat(" and Region='{0}' ", context.Request.Params["region"]);
        }
        if (!String.IsNullOrEmpty(context.Request.Params["HouseUse"]))
        {
            sb.AppendFormat(" and HouseUse='{0}' ", context.Request.Params["HouseUse"]);
        }
        if (!String.IsNullOrEmpty(context.Request.Params["buildingtype"]))
        {
            sb.AppendFormat(" and BuildingType='{0}' ", context.Request.Params["buildingtype"]);
        }
        if (!String.IsNullOrEmpty(context.Request.Params["businesstype"]))
        {
            if (context.Request.Params["businesstype"]!="-1")
                sb.AppendFormat(" and businesstype='{0}' ", context.Request.Params["businesstype"]);
            else
                sb.Append(" and (businesstype=10 or businesstype=20) ");
        }
        else
            sb.Append(" and (businesstype=10 or businesstype=20) ");
        if (!String.IsNullOrEmpty(context.Request.Params["Addtime"]))
        {
            sb.AppendFormat(" and {0}>='{1}' ", context.Request.Params["datetype"], context.Request.Params["Addtime"]);
        }
        if (!String.IsNullOrEmpty(context.Request.Params["Endtime"]))
        {
            sb.AppendFormat(" and {0}<'{1}' ", context.Request.Params["datetype"], DateTime.Parse(context.Request.Params["Endtime"].ToString()).AddDays(1));
        }
        if (!String.IsNullOrEmpty(context.Request.Params["s_area"]))
        {
            sb.AppendFormat(" and Area>={0} ", context.Request.Params["s_area"]);
        }
        if (!String.IsNullOrEmpty(context.Request.Params["e_area"]))
        {
            sb.AppendFormat(" and Area<={0} ", context.Request.Params["e_area"]);
        }
        if (!String.IsNullOrEmpty(context.Request.Params["s_price"]))
        {
            sb.AppendFormat(" and BargainPrice>={0} ", context.Request.Params["s_price"]);
        }
        if (!String.IsNullOrEmpty(context.Request.Params["e_price"]))
        {
            sb.AppendFormat(" and BargainPrice<={0} ", context.Request.Params["e_price"]);
        }
        if (!String.IsNullOrEmpty(context.Request.Params["keyword"]))
        {
            sb.AppendFormat(" and (Community like '%{0}%' or HouseAddress like '%{0}%') ", context.Request.Params["keyword"]);
        }
        
        //页码
        int strPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;//页码
        //页显示行数
        int strPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);//页记录数
        string strOrderField = "ContractCode";
        if (!String.IsNullOrEmpty(context.Request.Params["sort"]))
        {
            strOrderField = context.Request.Params["sort"];
        }
        DataSet ds = Chenxin.Lib.Business.DAL.System_TraceInfo.GetList(strPageIndex, strPageSize, strOrderField, "t_Contract_BaseInfo", sb.ToString(), "*", "*", true);

        context.Response.Write(string.Format("{{success:1,msg:'',data:{{count:{0},{1}}}}}", ds.Tables[1].Rows[0][0], Chenxin.Lib.Utility.JsonHelp.Convert2Json(ds.Tables[0])));
    }
    
    //导出全部的方法
    private void ExportAll(HttpContext context)
    {
        Guid city = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
        Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
        Guid businessdistrict = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
        Guid departs = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);

        //判断权限范围/////////////////////////////////////////////
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        if (CurrentUserInfo.ContainsPermit(Constants.Permit_BusinessMarket_All))
        {
            sb.Append(" (1=1) ");
        }
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_BusinessMarket_City))
        {
            sb.AppendFormat(" BargainCityId='{0}' ", CurrentUserInfo.CityId);
        }
        else if (CurrentUserInfo.ContainsPermit(Constants.Permit_BusinessMarket_Company))
        {
            sb.AppendFormat(" BargainCompanyId='{0}' ", CurrentUserInfo.CompanyId);
        }
        else
        {
            sb.Append(" 1=0 ");
        }


        if (departs != Guid.Empty)
            sb.AppendFormat(" AND (BuyerDepartId = '{0}')", departs);
        else if (businessdistrict != Guid.Empty)
        {
            Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item = null;
            string strCachkey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, businessdistrict);
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            item = cs.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachkey);
            if (!cs.Hit)
            {
                item = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(businessdistrict);
                if (item != null) cs.Set(strCachkey, item, DateTime.Now.AddDays(1));
            }

            if (item == null)
            {
                context.Response.Write(string.Format("{{success:'0',msg:'{0}',data:''}}", "获取商圈或分类数据丢失"));
                return;
            }
            sb.Append(" AND (EXISTS(");
            sb.Append("Select 1 from v_Hr_DepartmentInfo M ");
            sb.AppendFormat("WHERE (t_Contract_BaseInfo.BuyerDepartId = M.Departid AND M.DepartSrc like '{0}%'))) ", item.DepartSrc);
        }
        else if (company != Guid.Empty)
        {
            sb.AppendFormat(" and BargainCompanyId='{0}' ", company);
        }
        else if (city != Guid.Empty)
        {
            sb.AppendFormat(" and BargainCityId='{0}' ", city);
        }
        else
            sb.AppendFormat(" and BargainCompanyId='{0}' ", CurrentUserInfo.CompanyId);

        if (!String.IsNullOrEmpty(context.Request.Params["region"]))
        {
            sb.AppendFormat(" and Region='{0}' ", context.Request.Params["region"]);
        }
        if (!String.IsNullOrEmpty(context.Request.Params["HouseUse"]))
        {
            sb.AppendFormat(" and HouseUse='{0}' ", context.Request.Params["HouseUse"]);
        }
        if (!String.IsNullOrEmpty(context.Request.Params["buildingtype"]))
        {
            sb.AppendFormat(" and BuildingType='{0}' ", context.Request.Params["buildingtype"]);
        }
        if (!String.IsNullOrEmpty(context.Request.Params["businesstype"]))
        {
            if (context.Request.Params["businesstype"] != "-1")
                sb.AppendFormat(" and businesstype='{0}' ", context.Request.Params["businesstype"]);
            else
                sb.Append(" and (businesstype=10 or businesstype=20) ");
        }
        else
            sb.Append(" and (businesstype=10 or businesstype=20) ");
        if (!String.IsNullOrEmpty(context.Request.Params["Addtime"]))
        {
            sb.AppendFormat(" and {0}>='{1}' ", context.Request.Params["datetype"], context.Request.Params["Addtime"]);
        }
        if (!String.IsNullOrEmpty(context.Request.Params["Endtime"]))
        {
            sb.AppendFormat(" and {0}<'{1}' ", context.Request.Params["datetype"], DateTime.Parse(context.Request.Params["Endtime"].ToString()).AddDays(1));
        }
        if (!String.IsNullOrEmpty(context.Request.Params["s_area"]))
        {
            sb.AppendFormat(" and Area>={0} ", context.Request.Params["s_area"]);
        }
        if (!String.IsNullOrEmpty(context.Request.Params["e_area"]))
        {
            sb.AppendFormat(" and Area<={0} ", context.Request.Params["e_area"]);
        }
        if (!String.IsNullOrEmpty(context.Request.Params["s_price"]))
        {
            sb.AppendFormat(" and BargainPrice>={0} ", context.Request.Params["s_price"]);
        }
        if (!String.IsNullOrEmpty(context.Request.Params["e_price"]))
        {
            sb.AppendFormat(" and BargainPrice<={0} ", context.Request.Params["e_price"]);
        }
        if (!String.IsNullOrEmpty(context.Request.Params["keyword"]))
        {
            sb.AppendFormat(" and (Community like '%{0}%' or HouseAddress like '%{0}%') ", context.Request.Params["keyword"]);
        }

        //排序
        string strOrderField = "ContractDate desc";

        string strSql = "select * from t_Contract_BaseInfo where " + sb.ToString() + " order by " + strOrderField;
        //根据sql执行查询
        DataSet ds = Chenxin.Lib.Business.DAL.v_Contract_CommisionDetailInfo.GetList(strSql);

        string strHTML = GetHtml(ds.Tables[0]);

        ExportByServce(context, strHTML);
    }
    
    //导出全部的HTML
    private string GetHtml(DataTable dt)
    {
        StringBuilder sb = new StringBuilder();
        sb.Append("<table class=\"tabsorternew table_archive\"><tr>");
        sb.Append("<th style=\"width:120px;\">成交编号</th>");
        sb.Append("<th style=\"width:120px;\" >成交日期</th>");
        sb.Append("<th style=\"width:80px;\" >成交类别</th>");
        sb.Append("<th style=\"width:100px;\" >区域</th>");
        sb.Append("<th style=\"width:200px;\" >小区名称</th>");
        sb.Append("<th style=\"width:250px;\" >地址</th>");
        sb.Append("<th style=\"width:100px;\" >成交价格</th>");
        sb.Append("<th style=\"width:100px;\">单价</th>");
        sb.Append("<th style=\"width:100px;\">面积</th>");
        sb.Append("<th style=\"width:110px;\">房型</th>");
        sb.Append("<th style=\"width:100px;\">竣工年份</th>");
        sb.Append("<th style=\"width:100px;\">房屋用途</th>");
        sb.Append("<th style=\"width:100px;\">房屋类型</th>");
        sb.Append("<th style=\"width:100px;\">装修情况</th></tr>");

        foreach (System.Data.DataRow dr in dt.Rows)
        {
            sb.Append("<tr>");
            sb.AppendFormat("<td >{0}</td>", DatasetHelper.GetValue(dr, "ContractCode", ""));
            sb.AppendFormat("<td >{0}</td>", DatasetHelper.GetValue(dr, "ContractDate", "").Split(' ')[0]);
            string businesstype = "";
            if (DatasetHelper.GetValue(dr, "BusinessType", "") == "10")
                businesstype = "买卖";
            else if (DatasetHelper.GetValue(dr, "BusinessType", "") == "20")
                businesstype = "出租";
            else if (DatasetHelper.GetValue(dr, "BusinessType", "") == "30")
                businesstype = "零散";
            else if (DatasetHelper.GetValue(dr, "BusinessType", "") == "40")
                businesstype = "其他";
            sb.AppendFormat("<td >{0}</td>", businesstype);
            sb.AppendFormat("<td >{0}</td>", DatasetHelper.GetValue(dr, "Region", ""));
            sb.AppendFormat("<td >{0}</td>", DatasetHelper.GetValue(dr, "Community", ""));
            sb.AppendFormat("<td >{0}</td>", DatasetHelper.GetValue(dr, "HouseAddress", ""));
            sb.AppendFormat("<td >{0}</td>", DatasetHelper.GetValue(dr, "BargainPrice", (decimal)0));
            sb.AppendFormat("<td >{0}</td>", DatasetHelper.GetValue(dr, "BargainUnitPrice", (decimal)0));
            sb.AppendFormat("<td >{0}</td>", DatasetHelper.GetValue(dr, "Area", (decimal)0));
            sb.AppendFormat("<td >{0}</td>", DatasetHelper.GetValue(dr, "HouseType", "").Replace("/", ","));
            sb.AppendFormat("<td >{0}</td>", DatasetHelper.GetValue(dr, "CompleteYear", ""));
            sb.AppendFormat("<td >{0}</td>", DatasetHelper.GetValue(dr, "HouseUse", ""));
            sb.AppendFormat("<td >{0}</td>", DatasetHelper.GetValue(dr, "BuildingType", ""));
            sb.AppendFormat("<td >{0}</td>", DatasetHelper.GetValue(dr, "Fitment", ""));
            sb.Append("</tr>");
        }

        return sb.ToString();
    }
}